﻿var zombies = zombies || {};

zombies.CreateAdv = function () {
    var self = this;
    //cbb
    self.cbbMediatypes = ko.observableArray();
    self.cbbCategories = ko.observableArray();
    self.selectedCategories = ko.observableArray();

    //advertise
    self.Title = ko.observable();
    self.PreviewImg = ko.observable();
    self.ProductName = ko.observable();
    self.Description = ko.observable();
    self.ShortDes = ko.observable();
    self.MediaTypeId = ko.observable();
    self.MediaLink = ko.observableArray();
    self.IsUploaded = ko.observable(false);
    self.Accept = ko.computed(function () {
        var mt = ko.utils.arrayFirst(self.cbbMediatypes(), function (item) {
            return item.MediaTypeId === self.MediaTypeId();
        });
        if (mt === null) return ko.observable('image/*');
        return mt.Name;
    });

    self.Token = ko.observable();
    self.PostUrl = ko.observable();
    self.CurrentAdvId = ko.observable();

    //chanel
    self.ChannelName = ko.observable();
    self.ChannelCover = ko.observable();
    self.About = ko.observable();
    self.PubId = ko.observable();

    self.doSubmit = function () {
        var dataToSave = {
            Title: self.Title,
            Description: CKEDITOR.instances['ckeditor-des'].getData(),
            PublisherId: self.PubId,
            Categories: self.selectedCategories,
            MediaTypeId: self.MediaTypeId,
            PreviewImg: self.PreviewImg,
            MediaLink: self.MediaLink,
            ShortDes: self.ShortDes,
            ProductName: self.ProductName
        };
        $.ajax({
            type: "POST",
            url: "/api/AdminAdv/PostAdvertise",
            data: ko.toJSON(dataToSave), //Convert the Observable Data into JSON
            contentType: "application/json",
            dataType: 'json'
        }).done(function (data) {
            toastr.success('Add Book sucessfull !');
            if (self.Accept() === 'Video') {
                self.CurrentAdvId(data);
            } else {
                window.location.replace('http://' + window.location.host + '/publisher');
            }
        }).fail(function () {
            toastr.error('Add Book Failed !');
        });
    };

    self.getToken = function () {
        $.ajax({
            url: '/api/AdminAdv/GetYoutubeAccessToken',
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        }).done(function (data) {
            self.Token(data.Token);
            self.PostUrl(data.Url + '?nexturl=' + window.location.href);
        }).error(function () {
            toastr.error('Fail to get token');
        })
    };
};


//upload  function
ko.bindingHandlers.ThumUpload = {
    init: function (element, valueAccessor) {
        $('#uploadThum').after('<div class="progress" style="display: none; width: 50%"><div class="bar"></div><div class="percent">0%</div></div><div class="progressError"></div>');
    },
    update: function (element, valueAccessor, allBindingsAccessor, createAdvViewModel, bindingContext) {
        var options = ko.utils.unwrapObservable(valueAccessor()),
            property = ko.utils.unwrapObservable(options.property),
            url = ko.utils.unwrapObservable(options.url);

        if (property && url) {
            $(element.form).change(function () {
                if (element.files.length) {
                    var pre = $('#prethum');
                    $.loadPreviewImg(element, pre);
                }
            });
            $(element.form).submit(function () {
                if ($(element.form).valid() && element.files.length) {
                    var $this = $(element),
                        filename = $this.val();
                    var time = new Date($.now());
                    var fname = time.getTime() + $(element).prop("files")[0].name;
                    createAdvViewModel.PreviewImg("../Advertise/PreviewImgs/" + fname);
                    $(element.form).ajaxSubmit({
                        url: url,
                        enctype: "multipart/form-data",
                        type: "POST",
                        dataType: "json",
                        data: {fname: fname },
                        headers: { "Content-Disposition": "attachment; filename=" + filename },
                        beforeSubmit: function () {
                            $(".progress").show();
                            $(".progressError").hide();
                            $(".bar").width("0%")
                            $(".percent").html("0%");
                        },
                        uploadProgress: function (event, position, total, percentComplete) {
                            var percentVal = percentComplete + "%";
                            $(".bar").width(percentVal)
                            $(".percent").html(percentVal);
                        },
                        success: function (data) {
                            $(".progress").hide();
                            $(".progressError").hide();
                            $('html, body').animate({
                                scrollTop: $("#step1").offset().top - 200
                            }, 1000);
                            $('#step1').fadeOut(1000, function () {
                                var type = createAdvViewModel.Accept();
                                if (type === 'Video') {
                                    createAdvViewModel.getToken();
                                    createAdvViewModel.doSubmit();
                                    $('#step2-video').fadeIn(1000);
                                }
                                if (type === 'Flash') {
                                    $('#step2-flash').fadeIn(1000);
                                }
                                if (type === 'Images') {
                                    $('#step2-img').fadeIn(1000);
                                }
                            });
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            $(".progress").hide();
                            $("div.progressError").html(jqXHR.responseText);
                        }
                    });
                }
                return false;
            });
        }
    }
}

       
//load control
var loadAllCategory = function () {
    createAdvViewModel.cbbCategories.removeAll();
    $.ajax({
        url: '/api/AdminCategory/GetAllCategories',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (items) {
        $.each(items, function (idx, item) {
            createAdvViewModel.cbbCategories.push(new zombies.Category(item));
        });
    }).error(function () {
        toastr.error('error load categories');
    })
};


var loadAllMediatypes = function () {
    createAdvViewModel.cbbMediatypes.removeAll();
    $.ajax({
        url: '/api/AdminMediaType/GetAllMediatypes',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (items) {
        var tmp = createAdvViewModel.cbbMediatypes();
        $.each(items, function (idx, item) {
            tmp.push(new zombies.MediaType(item));
        });
        createAdvViewModel.cbbMediatypes.valueHasMutated();
    }).error(function () {
        toastr.error('error load mediatypes');
    })
};

var loadChanel = function () {
    $.ajax({
        type: "GET",
        url: "/api/Publisher/GetCurrentChannel",
        contentType: "application/json",
        dataType: 'json'
    }).done(function (item) {
        createAdvViewModel.PubId(item.PubId);
        createAdvViewModel.ChannelName(item.ChannelName);
        if (item.ChanelCover === null) createAdvViewModel.ChannelCover('../Advertise/DefaultAssets/default_cover.jpg');
        else createAdvViewModel.ChannelCover(item.ChannelCover);
        createAdvViewModel.About(item.About);
    }).fail(function () {
    });
};

var createAdvViewModel;
$(document).ready(function () {
    createAdvViewModel = new zombies.CreateAdv();
    loadAllCategory();
    loadAllMediatypes();
    loadChanel();

    ko.applyBindings(createAdvViewModel, document.getElementById("content_publisher"));
    
    //upload event
    var settingsImages = {
        url: "/api/AdminAdv/PostACF",
        method: "POST",
        allowedTypes: "jpg,png,gif",
        fileName: "myfile",
        multiple: true,
        onSuccess: function (files, data, xhr) {
            createAdvViewModel.MediaLink.push('../Advertise/' + data);
        },
        onError: function (files, status, errMsg) {
            alert("Upload Failed");
        }
    }

    var settingsFlash = {
        url: "/api/AdminAdv/PostACF",
        method: "POST",
        allowedTypes: "swf",
        fileName: "myfile",
        multiple: false,
        onSuccess: function (files, data, xhr) {
            createAdvViewModel.MediaLink.push('../Advertise/' + data);
        },
        onError: function (files, status, errMsg) {
            alert("Upload Failed");
        }
    }
    $("#imagesfileupload").uploadFile(settingsImages);
    $("#flashfileupload").uploadFile(settingsFlash);
});

var status = $.getUrlParams("status");
var videoId = $.getUrlParams("id");
var advId = $.getUrlVars("advid");
if (status == 200) {
    var dataVideo = { AdvId: advId, MediaLink: videoId };
    $.ajax({
        type: "PUT",
        url: "/api/AdminAdv/PutVideoAdvertise",
        data: ko.toJSON(dataVideo), //Convert the Observable Data into JSON
        contentType: "application/json",
        dataType: 'json'
    }).done(function () {
        window.location.replace('http://' + window.location.host + '/home/index');
    }).fail(function () {
        toastr.error('Edit Advertise Failed !');
    });

}